extends CharacterBody2D

@export var move_speed: float = 300.0
@onready var anim: AnimatedSprite2D = get_node("AnimatedSprite2D")
var is_game_over: bool = false
@export var bullet_Scene: PackedScene
@onready var timer_load_scene: Timer = get_node("Timer_LoadScene")

#音频
@onready var run_audio: AudioStreamPlayer = get_node("AudioStreamPlayer_Run")
@onready var game_over_audio: AudioStreamPlayer = get_node("AudioStreamPlayer_GameOver")
@onready var gun_audio: AudioStreamPlayer = get_node("AudioStreamPlayer_Gun")


func _ready() -> void:
	print("Player ready")


func _process(delta: float) -> void:
	if (is_game_over):
		if run_audio.playing:
			run_audio.stop()
		return
	velocity = Input.get_vector("left", "right", "up", "down") * delta * move_speed * 100
	move_and_slide()
	if (velocity.is_zero_approx()):
		anim.animation = "idle"
		if run_audio.playing:
			run_audio.stop()
	else:
		anim.animation = "run"
		if !run_audio.playing:
			run_audio.play()


func onGameOver() -> void:
	if is_game_over:
		return
	is_game_over = true
	anim.play("die")
	print("Game Over")
	MessageCenter.send(self, "game_over", true)
	game_over_audio.play()
	timer_load_scene.start()
	

func _on_timer_timeout() -> void:
	#print("Timer timeout")
	if (velocity != Vector2.ZERO or is_game_over):
		return
	var bullet_node = bullet_Scene.instantiate()
	bullet_node.position = position + Vector2(32, -1)
	#get_parent().add_child(bullet_node)
	get_tree().current_scene.add_child(bullet_node)
	gun_audio.play()
	anim.play("shoot")


func _load_scene_timeout() -> void:
	get_tree().reload_current_scene()
